﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AForge;
using AForge.Controls;
using AForge.Video;
using AForge.Video.DirectShow;//调用摄像头
using Size = System.Drawing.Size;
using System.Windows.Media.Imaging;
using ZXing;

namespace EquipmentMS
{
    public partial class returnAssets : Form
    {
        private FilterInfoCollection videoDevices;
        private VideoCaptureDevice videoSource;
        private int i = -1;
        public returnAssets()
        {
            InitializeComponent();
        } 
        //连接摄像头一
        private void CameraConn()
        {
            VideoCaptureDevice videoSource = new VideoCaptureDevice(videoDevices[0].MonikerString);
            videoSource.DesiredFrameSize = new System.Drawing.Size(320, 240);
            videoSource.DesiredFrameRate = 1;

            videoSourcePlayer1.VideoSource = videoSource;
            videoSourcePlayer1.Start();
        }
        private void returnAssets_Load(object sender, EventArgs e)
        {
            try
            {
                // 枚举所有视频输入设备
                videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);

                if (videoDevices.Count == 0)
                    throw new ApplicationException();

                foreach (FilterInfo device in videoDevices)
                {
                    //tscbxCameras.Items.Add(device.Name);
                    //textBoxC.AppendText("摄像头" + i + "初始化完毕..." + "\n");
                    //textBoxC.ScrollToCaret();
                    i++;
                }
                if (i < 0)
                {
                    MessageBox.Show("没有可用的摄像头设备");
                }
                else
                { //调用连接摄像头
                    CameraConn();

                }

                //tscbxCameras.SelectedIndex = 0;

            }
            catch (ApplicationException)
            {
                //tscbxCameras.Items.Add("No local capture devices");
                videoDevices = null;
            }
        }
        /// <summary>
        /// 解码二维码
        /// </summary>
        /// <param name="barcodeBitmap">待解码的二维码图片</param>
        /// <returns>扫码结果</returns>
        private string DecodeQrCode(Bitmap barcodeBitmap)
        {
            BarcodeReader reader = new BarcodeReader();
            reader.Options.CharacterSet = "UTF-8";
            var result = reader.Decode(barcodeBitmap);
            return (result == null) ? null : result.Text;
        }
        /// 将 BitmapSource 转化为 Bitmap
        /// </summary>
        /// <param name="source"/>要转换的 BitmapSource
        /// <returns>转化后的 Bitmap</returns>
       private Bitmap ToBitmap( BitmapSource source)
        { 
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                BitmapEncoder encoder = new BmpBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(source));
                encoder.Save(ms);
                return new System.Drawing.Bitmap(ms);
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
           


        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                if (videoSourcePlayer1.IsRunning)
                {
                    
                    BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                                    videoSourcePlayer1.GetCurrentVideoFrame().GetHbitmap(),
                                    IntPtr.Zero,
                                     System.Windows.Int32Rect.Empty,//System.Drawing.Imaging;
                                    BitmapSizeOptions.FromEmptyOptions());
                    PngBitmapEncoder pE = new PngBitmapEncoder();
                    string ret = DecodeQrCode(ToBitmap(bitmapSource));
                    if (ret.Trim()!="")
                    {
                        this.timer1.Stop();
                        if (MessageBox.Show("归还成功！", "MessageBoxButtons.OK")==DialogResult.OK)
                        {
                            //修改使用情况
                            try
                            {
                                string sql = string.Format("update  tb_zcMain set syqk='未使用' where syqk='使用中' and bh='{0}'", ret);
                                DBHelper.ExecuteNonQuery(sql);
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show("加载列表时出现异常，请联系管理员！\n原因：" + ex.Message);
                            }
                            this.timer1.Enabled = true;
                            //调用主窗口中的查询方法，已达刷新数据的作用
                            MainForm mainForm;
                            mainForm = (MainForm)this.Owner;
                            mainForm.DataBindGridViewList();
                            //关闭当前窗口
                            this.Close();
                            
                        }
                       
                        
                       
                    }
                    
                    

                }
            }
            catch (Exception ex)
            {
                
            }
        }

        private void returnAssets_FormClosing(object sender, FormClosingEventArgs e)
        {
            
            videoSourcePlayer1.SignalToStop();
                videoSourcePlayer1.WaitForStop();
               
        }
    }

}
